package com.example.demo07cache.listener;

import com.example.demo07cache.config.MyRedisConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisKeyExpiredEvent;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * 1.向容器中注入 {@link MyRedisConfig#keyExpirationEventMessageListener(org.springframework.data.redis.listener.RedisMessageListenerContainer)}
 * 2.写一个类实现 {@link ApplicationListener}
 * 3.监听关心的事件 {@link RedisKeyExpiredEvent}
 * 4.测试命令 {english:activity:student:1001 wang ex 10}
 */
@Component
public class RedisKeyExpirationListener implements ApplicationListener<RedisKeyExpiredEvent> {

    @Override
    public void onApplicationEvent(RedisKeyExpiredEvent event) {
        // user:1001  --> 1001
        // english:activity:student:1001  -->  activity:student:1001
        System.out.println(StringUtils.toEncodedString(event.getId(), StandardCharsets.UTF_8));
        // user:1001  --> user
        // english:activity:student:1001  -->  english
        System.out.println(event.getKeyspace());
        // user:1001  --> user:1001
        // english:activity:student:1001  -->  english:activity:student:1001
        System.out.println(StringUtils.toEncodedString(event.getSource(), StandardCharsets.UTF_8));
        // 时间戳  -->  1625243519693
        System.out.println(event.getTimestamp());
    }
}

